<template>
  <view class="leave-list-container">
    <view class="search-header">
      <uni-datetime-picker 
        type="date" 
        v-model="queryParams.beginTime" 
        :clear-icon="false"
        placeholder="开始日期"
      />
      <text class="date-separator">至</text>
      <uni-datetime-picker 
        type="date" 
        v-model="queryParams.endTime" 
        :clear-icon="false"
        placeholder="结束日期"
      />
      <button type="primary" size="mini" @click="handleQuery">查询</button>
      <button type="default" size="mini" @click="resetQuery">重置</button>
    </view>
    
    <view class="list-content">
      <view class="list-item" v-for="(item, index) in leaveList" :key="index">
        <view class="item-date">
          <text class="date">{{ formatShortDate(item.startTime) }}</text>
          <text class="date-range">至</text>
          <text class="date">{{ formatShortDate(item.endTime) }}</text>
        </view>
        <view class="item-info">
          <view class="info-row">
            <text class="info-label">请假类型：</text>
            <text class="info-value">{{ getLeaveTypeText(item.leaveType) }}</text>
          </view>
          <view class="info-row">
            <text class="info-label">请假天数：</text>
            <text class="info-value">{{ calculateDays(item.startTime, item.endTime) }}天</text>
          </view>
          <view class="info-row">
            <text class="info-label">申请原因：</text>
            <text class="info-value">{{ item.reason || '-' }}</text>
          </view>
        </view>
        <view class="item-status" :class="getStatusClass(item.status)">
          {{ getStatusText(item.status) }}
        </view>
      </view>
      
      <uni-load-more :status="loadMoreStatus" @clickLoadMore="loadMore"></uni-load-more>
    </view>
    
    <view class="action-buttons">
      <button type="primary" @click="goToLeave">新增请假申请</button>
    </view>
  </view>
</template>

<script>
import { listLeave } from "@/api/system/attendance";

export default {
  name: "LeaveList",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 总条数
      total: 0,
      // 请假记录列表
      leaveList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        beginTime: this.getLastMonthDate(),
        endTime: this.getCurrentDate()
      },
      // 加载更多状态
      loadMoreStatus: 'more'
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询请假记录列表 */
    getList() {
      this.loading = true;
      this.loadMoreStatus = 'loading';
      
      // 确保查询参数包含当前用户ID
      const currentUserId = this.$store.getters.id;
      
      this.queryParams = {
        ...this.queryParams,
        userId: currentUserId // 添加当前用户ID
      };
      
      listLeave(this.queryParams).then(response => {
        this.leaveList = this.queryParams.pageNum > 1 ? 
          this.leaveList.concat(response.rows) : response.rows;
        this.total = response.total;
        this.loading = false;
        this.loadMoreStatus = this.leaveList.length >= this.total ? 'noMore' : 'more';
      }).catch(error => {
        console.error('获取请假记录失败:', error);
        this.loading = false;
        this.loadMoreStatus = 'noMore';
      });
    },
    // 搜索按钮操作
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    // 重置按钮操作
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        beginTime: this.getLastMonthDate(),
        endTime: this.getCurrentDate()
      };
      this.getList();
    },
    // 加载更多
    loadMore() {
      if (this.loadMoreStatus === 'noMore') return;
      this.queryParams.pageNum += 1;
      this.getList();
    },
    // 获取当前日期
    getCurrentDate() {
      const now = new Date();
      const year = now.getFullYear();
      const month = (now.getMonth() + 1).toString().padStart(2, '0');
      const day = now.getDate().toString().padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
    // 获取一个月前的日期
    getLastMonthDate() {
      const now = new Date();
      now.setMonth(now.getMonth() - 1);
      const year = now.getFullYear();
      const month = (now.getMonth() + 1).toString().padStart(2, '0');
      const day = now.getDate().toString().padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
    // 格式化日期
    formatDate(dateStr) {
      if (!dateStr) return '';
      const date = new Date(dateStr);
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
    // 格式化短日期（仅月日）
    formatShortDate(dateStr) {
      if (!dateStr) return '';
      const date = new Date(dateStr);
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      return `${month}-${day}`;
    },
    // 计算请假天数
    calculateDays(startTime, endTime) {
      if (!startTime || !endTime) return 0;
      
      const start = new Date(startTime);
      const end = new Date(endTime);
      
      // 计算天数差异（毫秒转天数）
      const diffTime = Math.abs(end - start);
      const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
      
      return diffDays || 1; // 最少算1天
    },
    // 获取请假类型文本
    getLeaveTypeText(type) {
      const typeMap = {
        'personal': '事假',
        'sick': '病假',
        'annual': '年假',
        'compensatory': '调休',
        'other': '其他'
      };
      return typeMap[type] || '未知类型';
    },
    // 获取状态样式类
    getStatusClass(status) {
      const statusMap = {
        '0': 'status-pending',
        '1': 'status-approved',
        '2': 'status-rejected'
      };
      return statusMap[status] || 'status-pending';
    },
    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        '0': '待审批',
        '1': '已通过',
        '2': '已驳回'
      };
      return statusMap[status] || '待审批';
    },
    // 跳转到请假申请页
    goToLeave() {
      this.$tab.navigateTo('/pages/system/attendance/leave');
    }
  }
};
</script>

<style lang="scss" scoped>
.leave-list-container {
  padding: 15px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.search-header {
  background-color: #fff;
  border-radius: 10px;
  padding: 15px;
  margin-bottom: 15px;
  box-shadow: 0 1px 5px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  
  .date-separator {
    margin: 0 5px;
  }
  
  button {
    margin-left: 10px;
    margin-top: 10px;
  }
}

.list-content {
  background-color: #fff;
  border-radius: 10px;
  padding: 15px;
  margin-bottom: 15px;
  box-shadow: 0 1px 5px rgba(0, 0, 0, 0.1);
  
  .list-item {
    display: flex;
    padding: 15px 0;
    border-bottom: 1px solid #eee;
    
    &:last-child {
      border-bottom: none;
    }
    
    .item-date {
      width: 70px;
      text-align: center;
      display: flex;
      flex-direction: column;
      justify-content: center;
      
      .date {
        font-size: 14px;
        font-weight: bold;
      }
      
      .date-range {
        font-size: 12px;
        color: #666;
        margin: 2px 0;
      }
    }
    
    .item-info {
      flex: 1;
      padding: 0 15px;
      
      .info-row {
        display: flex;
        margin-bottom: 5px;
        
        &:last-child {
          margin-bottom: 0;
        }
        
        .info-label {
          width: 80px;
          color: #666;
        }
        
        .info-value {
          flex: 1;
        }
      }
    }
    
    .item-status {
      width: 60px;
      height: 25px;
      line-height: 25px;
      text-align: center;
      border-radius: 12.5px;
      font-size: 12px;
      
      &.status-pending {
        background-color: #e1f3ff;
        color: #409eff;
      }
      
      &.status-approved {
        background-color: #e1f3d8;
        color: #67c23a;
      }
      
      &.status-rejected {
        background-color: #fde2e2;
        color: #f56c6c;
      }
    }
  }
}

.action-buttons {
  button {
    width: 100%;
    height: 45px;
    font-size: 16px;
  }
}
</style> 